package com.aruba.girlanime.delegate;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.view.View;

import com.daimajia.androidanimations.library.BaseViewAnimator;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;

/**
 * 拍照动画
 * Created by aruba on 2018/4/17.
 */

public class PhotoAnimeDelegate implements IAnimeDelegate {
    View iv_left;
    View iv_right;

    private boolean isInit;
    private int playDuration = 1000;
    private float translationWidth;

    @Override
    public void startAnime() {
        YoYo.with(new PhotoAnimator())
                .duration((long) (playDuration * (Math.random() + 1)))
                .repeatMode(ValueAnimator.REVERSE)
                .repeat(1)
                .playOn(iv_left);
        iv_left.setVisibility(View.VISIBLE);
        iv_right.setVisibility(View.VISIBLE);
    }

    @Override
    public void init(View... args) {
        iv_left = args[0];
        iv_right = args[1];

        iv_left.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (!isInit) {
                    isInit = true;
                    translationWidth = iv_left.getWidth();
                }
            }
        });
    }

    @Override
    public void stopAnime() {
        YoYo.with(Techniques.Swing).playOn(iv_left).stop();
        YoYo.with(Techniques.Swing).playOn(iv_right).stop();
    }

    @Override
    public void reset() {
        stopAnime();
    }

    /**
     * Photo的anime
     */
    public class PhotoAnimator extends BaseViewAnimator {

        @Override
        public void prepare(View target) {
            getAnimatorAgent().playTogether(
                    ObjectAnimator.ofFloat(iv_left, "translationX", -translationWidth, -translationWidth / 3),
                    ObjectAnimator.ofFloat(iv_right, "translationX", translationWidth, translationWidth / 3)
            );
        }
    }

}
